#include"touch.h"
#include"lcd.h"
#include"bmp.h"
#include"video.h"
#include"music.h"
#include"dir.h"
// 触摸屏初始化
void touchscreen_init(TouchScreen *ts)
{
	ts->fd = open("/dev/input/event0", O_RDWR);
	if(ts->fd < 0)
	{
		perror("open touchscreen fail");
		return ;
	}
	
	// 获取X， Y的坐标最大值
	if (ioctl(ts->fd, EVIOCGABS(ABS_X), &ts->abs_x) == -1) {//打开文件描述符对应文件，获取绝对X轴的请求，存入abs结构体里面
        perror("获取X轴参数失败");
        close(ts->fd);
        return ;
    }
    if (ioctl(ts->fd, EVIOCGABS(ABS_Y), &ts->abs_y) == -1) {
        perror("获取Y轴参数失败");
        close(ts->fd);
        return ;
    } 
}

void touchscreen_uninit(TouchScreen *ts)
{
	close(ts->fd);
}


// 按下响应(获取x和y的值，立即返回)
void ts_press(Coordinate *coor, TouchScreen *ts)
{
	// 定义输入事件结构体
    struct input_event buf;
	coor->x = -1, coor->y = -1;
    while(1)
    {
        // bzero(&buf, sizeof(buf));
        read(ts->fd, &buf, sizeof(buf));

		// 绝对事件（触摸屏）
        if(buf.type == EV_ABS && buf.code == ABS_X)
			coor->x = buf.value * 800 / ts->abs_x.maximum;

        if(buf.type == EV_ABS && buf.code == ABS_Y)
			coor->y = buf.value * 480 / ts->abs_y.maximum;
		
		if(coor->x != -1 && coor->y != -1)
			break;
    }
}

// 松开响应(离开屏幕，返回)
void ts_loosen(Coordinate *coor, TouchScreen *ts)
{
	// 定义输入事件结构体
    struct input_event buf;
	// coor->x = -1, coor->y = -1;//加上这行触摸屏会卡顿（快点快松），
    while(1)
    {
        // bzero(&buf, sizeof(buf));
        read(ts->fd, &buf, sizeof(buf));

		// 按键事件
        if(buf.type == EV_KEY && buf.code == BTN_TOUCH)
		{
			if(buf.value == 0 && coor->x != -1 && coor->y != -1)
				break;
		}

		// 绝对事件（触摸屏）
        if(buf.type == EV_ABS && buf.code == ABS_X)
			coor->x = buf.value * 800 / ts->abs_x.maximum;

        if(buf.type == EV_ABS && buf.code == ABS_Y)
			coor->y = buf.value * 480 / ts->abs_y.maximum;
    }
}

// 相册
void photo(LCD *lcd, TouchScreen *ts)
{
	int count ;
	// char *bmp[7] = {
	// 	"image/1.bmp",
	// 	"image/2.bmp",
	// 	"image/3.bmp",
	// 	"image/4.bmp",
	// 	"image/5.bmp",
	// 	"image/6.bmp",
	// 	"image/7.bmp",
	// };
	char (*bmp)[256] = (char (*)[])malloc(sizeof(char)*100*256);
	if (bmp == NULL)
	{
		perror("malloc error");
		exit(1); 
	}

	
	count = retrieve_file("./image",bmp,".bmp",100);
	
	Coordinate coor;
	
	int index = 0;
	anybmp(0, 0, bmp[index], lcd);
	while(1)
	{
		// 获取坐标
		ts_press(&coor, ts);
		printf("(%d, %d)\n", coor.x, coor.y);
		
		if(coor.y>400 && coor.y<480) //退出
			break;
		else if(coor.x>0 && coor.x<400)
			index = (--index == -1) ? count-1 : index;
		else if(coor.x>400 && coor.x<800)
			index = (++index == count) ? 0 : index;
		
		anybmp(0, 0, bmp[index], lcd);
	}
	free(bmp);
}